import React, { useEffect, useState } from 'react';
import './App.scss';
import TopPic from './static/pic_report@2x.png';
import TodayTitle from './static/今天我学习了@2x.png';
import PinkLink from './static/pic_link copy 2@2x.png';
import Voice from './static/宝贝的口语表达@2x.png';
import Gain from './static/今日学习收获@2x.png';
import IconError from './static/ico_right_d copy@2x.png';
import IconRight from './static/ico_right_d@2x.png';
import Share from './static/tab_ico_report_h copy@2x.png';
import IconVoice from './static/ico_voice_d@2x.png';
import ActiveIcon from './static/btn_voice 2.gif';
import ShareImg from './static/pic_popup@2x.png';
import Back from './static/back.png';
import HomeWork from './static/我的作品@2x.png';
import PlayBtn from './static/btn_play_h@2x.png';
import StopBtn from './static/btn_stop_h@2x.png';
import axios from 'axios';
import { Toast } from 'antd-mobile';
import urllib from 'url';

// import VConsole from 'vconsole/dist/vconsole.min.js'; //import vconsole
// new VConsole(); // 初始化

const Qs = require('qs');

axios.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded';

class App extends React.Component {
  state = {
    learn_what: [], // 测试引导语
    harvest: [], // 练一练
    oral: [], // 读一读,
    user_work: '',

    current: 0,
    isPlaying: false,
    xwShareShow: false,
  };

  async componentDidMount() {
    const { u_id, id } = this.getQuery();
    await this.getUserTranscript({ u_id, id });
  }

  getQuery() {
    const url = window.location.href;
    if (!urllib.parse(url, true).query) {
      return Toast.fail('分享失败');
    }
    return urllib.parse(url, true).query;
  }

  share = async () => {
    /* eslint-disable*/
    if (uni.postMessage) {
      uni.getEnv(function(res) {
        console.log('当前环境：' + JSON.stringify(res));
      });
      uni.postMessage({
        data: {
          action: 'message',
        },
      });
      uni.navigateBack();
      return;
    } else {
      this.setState({
        xwShareShow: true,
      });
    }
  };
  back = () => {
    /* eslint-disable*/
    if (uni.navigateBack) {
      uni.navigateBack();
    } else {
      window.history.go(-1);
    }
  };

  getUserTranscript = async ({ u_id, id }) => {
    try {
      const url = 'https://language.fangti.com/api/lesson/user_transcript';
      let { data } = await axios.post(
        url,
        Qs.stringify({
          id,
          u_id,
        }),
      );
      if (data.code === 1) {
        const { harvest, oral, learn_what, user_work } = data.data;
        this.setState({
          harvest,
          oral,
          learn_what,
          user_work,
        });
      } else {
        Toast.fail(data.message, 3);
      }
    } catch (e) {
      console.log(e);
      Toast.fail('服务器异常', 3);
    }
  };

  async playAudio(src, index) {
    const audio = document.querySelector('#audio');
    this.setState({
      isPlaying: false,
      current: index,
    });
    // audio.src = 'https://fangtiyuwen.oss-cn-beijing.aliyuncs.com/admin_files/b1baec16cb9db8b76cab24c26b5b52b1.mp3';
    audio.src = src;
    console.log(audio);

    audio.play().then(
      res => {
        console.log('成功播放');
      },
      err => {
        console.log('播放错误');
      },
    );
  }

  onEnded = e => {
    this.setState({
      isPlaying: false,
    });
    console.log('音频播放结束', e);
  };

  onPlaying = e => {
    this.setState({
      isPlaying: true,
    });
    console.log('音频正在播放', e);
  };

  onCanPlay = e => {
    console.log('音频可以播放', e);
  };

  onError = e => {
    console.log('error', e);
  };

  timeUpdate = e => {
    console.log(e);
  };

  render() {
    const {
      harvest,
      oral,
      learn_what,
      isPlaying,
      current,
      user_work,
    } = this.state;
    return (
      <div
        className={ ['App', this.state.xwShareShow && 'wx-share-show'].join(' ') }
      >
        <audio
          id="audio"
          onCanPlay={ this.onCanPlay }
          onPlaying={ this.onPlaying }
          onEnded={ this.onEnded }
          onTimeUpdate={ this.timeUpdate }
          onError={ this.onError }
        />
        <div className="wrap">
          <img src={ Back } className="back" alt="" onTouchEnd={ this.back }/>

          <section className="header">
            <img className="top-pic" src={ TopPic } alt=""/>
            <img src={ TodayTitle } alt="" className="today-title"/>
          </section>

          { learn_what.length > 0 && <section className="today-learn">
            { learn_what.map(({ guide }, index) => (
              <p key={ index }>{ guide }</p>
            )) }
          </section> }

          { oral.length > 0 && <>
            <section className={ 'pink-link' }>
              <img src={ PinkLink } alt=""/>
              <img src={ PinkLink } alt=""/>
            </section>

            <section className={ 'voice' }>
              <img src={ Voice } alt="" className="voice-img"/>
              <p>规范朗读、积极思考、完整表达</p>

              <ul>
                { oral.map(({ guide, recording }, index) => (
                  <section key={ index }>
                    <li className={ 'left' }>
                      <img
                        className={ 'avatar' }
                        src="https://fangtiyuwen.oss-cn-beijing.aliyuncs.com/admin_images/cf187de32e8ad52b9c15fba01503e871.jpg"
                        alt=""
                      />
                      <span>{ guide }</span>
                    </li>

                    <li className={ 'right' }>
                      <img
                        className={ 'avatar' }
                        src="https://fangti-mcdn.oss-cn-beijing.aliyuncs.com/appstatic/img/default_head.png"
                        alt=""
                      />
                      <span onClick={ () => this.playAudio(recording, index) }>
                      <img
                        src={
                          isPlaying && current === index
                            ? ActiveIcon
                            : IconVoice
                        }
                        alt=""
                        className="icon-voice"
                      />{ ' ' }
                        点击播放
                    </span>
                    </li>
                  </section>
                )) }
              </ul>
            </section>
          </> }

          { harvest.length > 0 && <>
            <section className={ 'pink-link' }>
              <img src={ PinkLink } alt=""/>
              <img src={ PinkLink } alt=""/>
            </section>

            <section className={ 'gain' }>
              <img src={ Gain } alt="" className="gain-title"/>
              <p>理解知识方法才能真正吸收</p>

              <ul>
                { harvest.map(({ content, is_correct, options, guide }, index) => (
                  <li key={ index }>
                    { is_correct === 1 ? (
                      <img src={ IconRight } alt=""/>
                    ) : (
                      <img src={ IconError } alt=""/>
                    ) }

                    <span>{ guide }</span>
                  </li>
                )) }
              </ul>
            </section>
          </>
          }

          { user_work && <>
            <section className={ 'pink-link' }>
              <img src={ PinkLink } alt=""/>
              <img src={ PinkLink } alt=""/>
            </section>

            <HomeWorks userWork={ user_work }/>
          </> }

          <footer onTouchStart={ this.share }>
            <img src={ Share } alt=""/>
            <span>分享到朋友圈</span>
          </footer>

          <div style={ { height: 120 } }/>
        </div>

        { this.state.xwShareShow && (
          <div
            className="wxShare"
            onClick={ () => this.setState({ xwShareShow: false }) }
          >
            <img src={ ShareImg } className="today-title" alt=""/>
          </div>
        ) }
      </div>
    );
  }
}

export default App;

const HomeWorks = props => {
  const [data, setData] = useState({
    startX: 0,
    marginLeft: 0,
    _marginLeft: 0,
    progressWidth: '',
    btnWidth: 0,
    Max: 0,
    time: 0,
    audio: document.createElement('audio'),
    pause: true,
    btnList: [
      {
        y: 'btn_tick_s@2x',
        g: 'btn_tick_n@2x',
        e: 'ico_tick_h@2x.png',
        isSlected: false,
        name: 'right',
      },
      {
        y: 'btn_wrong_s@2x',
        g: 'btn_wrong_n@2x',
        e: 'ico_del_h@2x.png',
        isSlected: false,
        name: 'error',
      },
      {
        y: 'btn_circle_s@2x',
        g: 'btn_circle_n@2x',
        isSlected: false,
        e: 'pic_circle_h@2x.png',
        name: 'round',
      },
      {
        y: 'btn_line_s@2x',
        g: 'btn_line_n@2x',
        e: 'pic_line_h@2x.png',
        isSlected: false,
        name: 'line',
      },
      {
        y: 'btn_example_s@2x',
        g: 'btn_example_n@2x',
        e: 'btn_example_n@2x.png',
        isSlected: false,
        name: 'expm',
      },
    ],
    bg: 'pic_read@2x.png',
    ctx: {},
    editSize: 60,
    originCanvasWidth: 335,
    correct_display: '',
    show_correct_display: false,
    c_name: '',
    l_name: '',
    nick_name: '',
    picture: '',
    comment_audio: '',
    comment_content: '',
    done: [],
    ePath: [],
    backImgInfo: { width: 0, height: 0 },
    _width: 0,
  });

  const touchStart = e => {
    const { pageX } = e.touches[0];
    const { marginLeft } = data;

    Pause();

    setData({
      ...data,
      startX: pageX,
      _marginLeft: marginLeft,
    });

    localStorage._marginLeft = marginLeft;
    localStorage.startX = pageX;
  };

  const touchMove = e => {
    const { pageX } = e.touches[0];
    const progressWidth = document.querySelector('.audio-progress').offsetWidth;
    const btnWidth = document.querySelector('.btn').offsetWidth;
    const _width = progressWidth - btnWidth;
    const Max = (_width / progressWidth) * 100;
    const startX = localStorage.startX - 0;
    const _marginLeft = localStorage._marginLeft - 0;

    const Min = 0;
    const change = pageX - startX;
    let marginLeft = _marginLeft + (change / _width) * 100;

    marginLeft = marginLeft > Max ? Max : marginLeft;
    marginLeft = marginLeft < Min ? Min : marginLeft;

    setData({
      ...data,
      marginLeft,
    });
  };

  const touchEnd = () => {
    const { audio, marginLeft } = data;
    const { duration } = audio;
    const progressWidth = document.querySelector('.audio-progress').offsetWidth;
    const btnWidth = document.querySelector('.btn').offsetWidth;
    const _width = progressWidth - btnWidth;
    const Max = (_width / progressWidth) * 100;

    const currentTime = Math.floor((duration / Max) * marginLeft);
    console.log(currentTime);
    audio.currentTime = currentTime;
    play();
  };

  const play = () => {
    const { audio } = data;
    audio.play().then(r => {
      setData({
        ...data,
        pause: false,
        show_correct_display: false,
      });
    });
  };

  const Pause = () => {
    const { audio } = data;
    audio.pause();
    setData({
      ...data,
      pause: true,
    });
  };

  /////////////// canvas
  const downImgs = async urls => {
    return urls.map(async (item, key) => {
      return downloadFile(
        item.includes('https')
          ? item
          : 'https://fangti-mcdn.oss-cn-beijing.aliyuncs.com/appstatic/img/ft2/' +
          item,
      );
    });
  };

  const downloadFile = async url => {
    if (!url) {
      console.log(111, url);
      return;
    }
    return new Promise((resolve, reject) => {
      function getBase64Image(img) {
        const canvas = document.createElement('canvas');

        const ctx = canvas.getContext('2d');
        canvas.width = image.width;
        canvas.height = image.height;
        ctx.drawImage(img, 0, 0, img.width, img.height);
        const ext = img.src
          .substring(img.src.lastIndexOf('.') + 1)
          .toLowerCase();
        return canvas.toDataURL('image/' + ext);
      }

      const image = new Image();
      image.crossOrigin = '';
      image.src = url;
      image.onload = function() {
        const base64 = getBase64Image(image);

        resolve(base64);
      };
      //   let xhr = new XMLHttpRequest();
      //   xhr.responseType =  'blob';
      //
      //   console.log(url);
      //   xhr.onreadystatechange = () => {
      //     if (xhr.readyState === 4) {
      //       const blob = xhr.response;
      //       console.log(blob,xhr);
      //       if (blob) {
      //         resolve(URL.createObjectURL(blob));
      //       }
      //     }
      //   };
      //   xhr.open('get', url, true);
      //   xhr.send(null);
    });
  };

  const drawBack = async ({ backImgInfo, ePath }) => {
    const canvas = document.querySelector('.canvas');
    const ctx = canvas.getContext('2d');
    const { width, height, _height, _width } = backImgInfo;
    const img = new Image();
    img.src = ePath;
    ctx.drawImage(
      img,
      0,
      0,
      width,
      height,
      0,
      0,
      canvas.clientWidth,
      (canvas.clientWidth * height) / width,
    );
  };

  const backImgInfo = async ePath => {
    return new Promise(async resolve => {
      const {
        clientWidth: canvasWidth,
        clientHeight: canvasHeight,
      } = document.querySelector('.canvas');
      const img = new Image();
      img.src = await ePath;
      img.onload = async e => {
        const { width, height } = img;

        let _width, _height;
        if (width < height) {
          _height = canvasHeight;
          _width = Math.floor((width * _height) / height);
        } else {
          _width = canvasWidth;
          _height = Math.floor((_width * height) / width);
        }
        setData({
          ...data,
          backImgInfo: {
            width,
            height,
            _height,
            _width,
          },
        });

        resolve({
          width,
          height,
          _height,
          _width,
        });
      };
    });
  };
  const drawEditor = async (x, y, btnIndex, ePath) => {
    let { editSize, originCanvasWidth } = data;
    const canvas = document.querySelector('.canvas');
    const { clientWidth: canvasWidth } = canvas;

    const ctx = canvas.getContext('2d');

    if (btnIndex === 4) return;

    const img = new Image();
    img.src = await ePath[btnIndex];
    const r = canvasWidth / originCanvasWidth;

    const _editSize = (editSize * r) / 2;

    x = x * r - _editSize / 2;
    y = y * r - _editSize / 2;
    ctx.drawImage(img, 0, 0, editSize, editSize, x, y, _editSize, _editSize);
  };

  const drawHistory = ({ curTime, ePath, marginLeft }) => {
    props.userWork.comment_content &&
    JSON.parse(props.userWork.comment_content).forEach(
      ({ x, y, btnIndex, time }) => {
        if (time >= curTime) return;
        drawEditor(x, y, btnIndex, ePath).then(r => {
          if (btnIndex === 4) {
            setData({
              ...data,
              marginLeft,
              show_correct_display: true,
              pause: false,
            });
          }
        });
      },
    );
  };

  const drawSteps = async (x, y, btnIndex) => {
    const { backImgInfo, ePath } = data;
    await drawBack({ backImgInfo, ePath: props.userWork.picture });
    await drawEditor(x, y, btnIndex, ePath);
    drawHistory();
  };

  useEffect(() => {
    const canvas = document.querySelector('.canvas');
    const ctx = canvas.getContext('2d');
    const { offsetWidth, offsetHeight } = canvas;
    canvas.height = offsetHeight;
    canvas.width = offsetWidth;
    const { btnList } = data;
    const eList = [...btnList.map(item => item.e), props.userWork.picture];
    Toast.loading('数据加载中');
    const src =
      'https://fangtiyuwen.oss-cn-beijing.aliyuncs.com/admin_files/2ff0721f89347ce62da9a2a3b4493ddc.mp3';
    const { audio, comment_audio } = data;
    // audio.src = src;
    audio.src = props.userWork.comment_audio;
    const progressWidth = document.querySelector('.audio-progress').offsetWidth;
    const btnWidth = document.querySelector('.btn').offsetWidth;
    const _width = progressWidth - btnWidth;
    const Max = (_width / progressWidth) * 100;

    console.log(1);

    downImgs(eList).then(ePath => {
      console.log(2);
      backImgInfo(props.userWork.picture).then(backImgInfo => {
        console.log(3);
        drawBack({ backImgInfo, ePath: props.userWork.picture });
        const { audio } = data;
        audio.onerror = e => {
          // Toast.fail('音频加载失败');
        };
        audio.oncanplay = e => {
        };
        audio.onplay = e => {
          console.log('开始播放');
          drawBack({ backImgInfo, ePath: props.userWork.picture });
        };
        audio.ontimeupdate = e => {
          let { currentTime, duration } = audio;
          console.log(audio.duration, audio.src);
          const marginLeft = (currentTime / duration) * Max;
          const time = Math.floor(currentTime);
          console.log(marginLeft);
          drawBack({ ePath: props.userWork.picture, backImgInfo }).then(r =>
            drawHistory({ curTime: time, ePath, marginLeft }),
          );
          setData({
            ...data,
            marginLeft,
            time,
            pause: false,
          });

          audio.onpause = e => {
            setData({
              ...data,
              marginLeft,
              time,
              pause: true,
            });
          };
        };

        audio.onended = e => {
          const { Max } = data;
          setData({
            ...data,
            marginLeft: Max,
            pause: true,
            show_correct_display: true,
          });
        };
      });
    });
    return () => {
    };
  }, [props.userWork]);

  return (
    <div className="homework">
      <img src={ HomeWork } className="today-title" alt=""/>
      <canvas className={ 'canvas' }/>
      { data.show_correct_display && props.userWork.correct_display && (
        <img src={ props.userWork.correct_display } className={ 'cr' } alt=""/>
      ) }
      {/*{<img src='https://fangti-mcdn.oss-cn-beijing.aliyuncs.com/appstatic/img/ft2/pic_circle_h@2x.png'  alt=""/>}*/ }
      <div className="audio" style={{display:props.userWork.comment_status === 2?'block':'none'}}>
        { data.pause ? (
          <img onClick={ play } className="audio-img" src={ PlayBtn } alt={ '' }/>
        ) : (
          <img className="audio-img" onClick={ Pause } src={ StopBtn } alt={ '' }/>
        ) }
        <div className="audio-progress">
          <div
            style={ { marginLeft: data.marginLeft + '%' } }
            className="btn"
            onTouchStart={ touchStart }
            onTouchMove={ touchMove }
            onTouchEnd={ touchEnd }
          />
        </div>
      </div>
    </div>
  );
};
